"""
Run this file to run the game.
"""

####IMPORTS####
import pygame, os
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((0,0), FULLSCREEN)
from qnd import *
from roy import Roy

####CONSTANTS####
FRAMERATE = 30
fonts = {'main':pygame.font.Font(None,24)}
####FUNCTIONS####
def play_level(level):
	"""Playes the level"""
	clock = pygame.time.Clock()
	roy = Roy((100,100))

	spr_inventory=load_image('inventory.png', alpha=False)
	
	#Create the main map from all the map files
	mainmap = []
	for i in range(11):
		column = []
		for j in range(11):
			column.append(load_tilemap(str(i).zfill(2)+str(j).zfill(2)))
		mainmap.append(column)
	mainmappos = [0,0] #The current position on the main map
	print mainmappos
	
	tilemap = mainmap[mainmappos[0]][mainmappos[1]]
	tileset = load_tileset('tileset_1.png')

	camera = Camera(screen)
	camera.x = -(screen.get_width()-tileset[0].get_width()*len(tilemap))/2
	camera.y = -(screen.get_height()-tileset[0].get_height()*len(tilemap[0]))/2
	
	squarewidth = tileset[0].get_width()*len(tilemap[0])
	squareheight = tileset[0].get_height()*len(tilemap[0])
	
	#The main loop
	while True:
		#Update Objects
		input.update()
		roy.update(input)
		
		#Move to next square in the mainmap when at the edge of the screen
		if roy.x < 0 and mainmappos[0] > 0:
			mainmappos[0] -= 1
			tilemap = mainmap[mainmappos[0]][mainmappos[1]]
			roy.x = squarewidth-1
		elif roy.x > squarewidth and mainmappos[0] < len(mainmap):
			mainmappos[0] += 1
			tilemap = mainmap[mainmappos[0]][mainmappos[1]]
			roy.x = 1
		if roy.y < 0 and mainmappos[1] > 0:
			mainmappos[1] -= 1
			tilemap = mainmap[mainmappos[0]][mainmappos[1]]
			roy.y = squareheight-1
		elif roy.y > squareheight and mainmappos[1] < len(mainmap[mainmappos[1]]):
			mainmappos[1] += 1
			tilemap = mainmap[mainmappos[0]][mainmappos[1]]
			roy.y = 1	
		#Drawing
		screen.fill((0,0,0))
		draw_tiles(screen, tilemap, tileset,camera)
		pygame.draw.rect(screen,(0,0,0),(-camera.x,-camera.y,squarewidth,squareheight), 4)
		draw_text(screen, "Tile: "+str(mainmappos),(10,10),fonts['main'],(0,0,0))
		draw_text(screen, "pos: "+str((roy.x,roy.y)),(10,30),fonts['main'],(255,255,255))
		roy.draw(screen,camera)
		if input.keys[K_e]:
			draw_image(screen, spr_inventory, ('c','c'), center=True, alpha=228)
		pygame.display.flip()
		
		#Limit the framerate
		clock.tick(FRAMERATE)

	
####INITIALIZE####
input = InputHandler()
screen.fill((120,40,40))
draw_text(screen, "ROY", ('c','c'),pygame.font.Font(None,240))
pygame.display.flip()
pygame.time.wait(1000)
draw_text(screen, "Loading Maps", ('c',600),pygame.font.Font(None,48))
pygame.display.flip()
play_level("level_1")
